<template>
  <div class="message-item user-message" :class="{ streaming: message.isStreaming }">
    <MessageHeader role-label="用户" :timestamp="message.timestamp" />

    <div class="message-content">
      <div class="message-text user" v-text="plainText"></div>

      <TTSControls 
        :enabled="ttsEnabled" 
        :is-playing="isPlaying"
        :audio-url="message.audioUrl"
        :has-content="!!message.content"
        @play="onPlay"
        @stop="onStop"
      />
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import MarkdownService from '@/services/MarkdownService.js'
import ttsService from '@/services/TTSService.js'
import MessageHeader from '@/components/MessageItem/components/MessageHeader.vue'
import TTSControls from '@/components/MessageItem/components/TTSControls.vue'

const props = defineProps({
  message: { type: Object, required: true },
  isPlaying: { type: Boolean, default: false },
  ttsEnabled: { type: Boolean, default: true }
})

const emit = defineEmits(['play-tts', 'stop-tts', 'update-audio-url'])


const plainText = computed(() => {
  if (!props.message || !props.message.content) return ''
  const content = typeof props.message.content === 'string' ? props.message.content : String(props.message.content)
  return content
})

const onPlay = async (done) => {
  if (!props.ttsEnabled) { done && done(); return }
  try {
    if (!props.message.audioUrl) {
      await generateTTS()
    }
    emit('play-tts', props.message.id)
  } catch (e) {
    console.error('User TTS generation failed:', e)
  } finally {
    done && done()
  }
}

const onStop = () => {
  emit('stop-tts')
}

const generateTTS = async () => {
  const text = MarkdownService.getPlainText(plainText.value)
  const audioUrl = await ttsService.generateAudio(text, props.message.id)
  emit('update-audio-url', props.message.id, audioUrl)
}

</script>

<style scoped>
@import './index.css';
</style>


